import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import customerApi from '@/api/sale/customer-api'
import tenantApi from '@/api/system/tenant-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const disabledOptions = [
      { label: '正常', value: false },
      { label: '停用', value: true }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '客户',
      api: customerApi,
      columns: [
        // { prop: 'tenantId', label: '租户', valueType: 'slot' },
        { prop: 'name', label: '客户名称', valueType: 'input' },
        { prop: 'contactName', label: '联系人', valueType: 'input' },
        { prop: 'contactMobile', label: '联系方式' },
        { prop: 'address', label: '联系地址' },
        { prop: 'disabled', label: '状态', slot: true, valueType: 'select', options: disabledOptions, permit: ['core:user:save'] },
        { prop: 'operation', label: '操作', slot: true }
      ],
      // 表单校验项规则
      rules: {
        // tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }],
        name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
        contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        contactMobile: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的联系方式', trigger: 'blur' }],
        disabled: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      other: {
        // 状态切换
        statusChanged: (row) => {
          const { username, disabled } = row
          ElMessageBox.confirm(`确认要${disabled ? '停用' : '启用'}"${username}"${ctx.title}吗？`, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true
          })
            .then(async () => {
              const res = await customerApi.save(row)
              if (res.success) {
                ElMessage.success(`${disabled ? '停用' : '启用'}成功`)
              } else {
                row.disabled = !disabled
              }
            })
            .catch(() => {
              row.disabled = !disabled
            })
        }
      }
    }))

    const data = reactive({
      ctx,
      disabledOptions,
      tenantOptions: []
    })


    const getTenant = async () => {
      const params = { filter: { disabled: false } }
      const res = await tenantApi.list(params)
      if (res.success) {
        data.tenantOptions = res.data?.records
      }
    }

    // init
    onMounted(() => {
      // getTenant()
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
